package cn.wei.reallyEnjoy.user.activity;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.List;

import cn.wei.reallyEnjoy.R;
import cn.wei.reallyEnjoy.app.LoginActivity;
import cn.wei.reallyEnjoy.app.RecordDetailActivity;
import cn.wei.reallyEnjoy.home.bean.DiaryBean;
import cn.wei.reallyEnjoy.home.bean.DiaryListBean;
import cn.wei.reallyEnjoy.home.bean.RecordBean;
import cn.wei.reallyEnjoy.user.adapter.MyCollectionAdapter;
import cn.wei.reallyEnjoy.user.adapter.MyDiaryAdapter;
import cn.wei.reallyEnjoy.utils.Constants;
import okhttp3.Call;

public class MyCollectionActivity extends AppCompatActivity implements View.OnClickListener {

    private LinearLayout myCollectionTitle;
    private ImageButton ibMyCollectionBack;
    private View SplitLine;
    private GridView gvMyCollection;
    private String uid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_collection);
        //去掉窗口标题
        getSupportActionBar().hide();
        findViews();
        SetDataForView();
    }

    private void SetDataForView() {
        SharedPreferences sp = this.getSharedPreferences("user", MODE_PRIVATE);
        uid = sp.getString("id", "");
        if (TextUtils.isEmpty(uid)){
            Toast.makeText(this, "未登录,请先登录", Toast.LENGTH_SHORT).show();
            new AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage("请先登录")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent=new Intent(MyCollectionActivity.this, LoginActivity.class); //使用getActivity得到当前Activity
                            startActivity(intent);
                            finish(); //销毁当前Activity（即一直按back返回也不会回到前一个Activity，直接回到桌面）

                        }
                    })
                    .setCancelable(false)
                    .show();
            return;
        }

        String url = Constants.MY_COLLECTION_URL+uid;
        OkHttpUtils.get()
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(MyCollectionActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        JSONObject jsonObject = JSON.parseObject(response);
                        String code = String.valueOf(jsonObject.get("code"));
                        if (TextUtils.equals(code,"0")){
                            //获取data节点
                            JSONObject  respData = (JSONObject) jsonObject.get("data");


                            List<Object> obj = (List<Object>) respData.get("userDiary");
                            if (obj.size()>0){
                                String data = String.valueOf(jsonObject.get("data"));
                                DiaryListBean diaryListBean = JSON.parseObject(data, DiaryListBean.class);
                                gvMyCollection.setAdapter(new MyCollectionAdapter(diaryListBean.getUserDiary(),MyCollectionActivity.this));
                                gvMyCollection.setOnItemClickListener(new AdapterView.OnItemClickListener(){
                                    @Override
                                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                                        //日志记录对象
                                        //TODO
                                        DiaryBean diaryBean = diaryListBean.getUserDiary().get(position);
                                        RecordBean recordBean = new RecordBean();

                                        //记录对象
                                        //TODO
                                        recordBean.setRecord_id(diaryBean.getId());
                                        recordBean.setImg(diaryBean.getContentImg());
                                        recordBean.setContent(diaryBean.getContent());
                                        recordBean.setTitle(diaryBean.getTitle());
                                        recordBean.setUname(diaryBean.getUname());
                                        recordBean.setUheadImg(diaryBean.getUheadImg());
                                        recordBean.setPrefer(diaryBean.getPrefer());
                                        recordBean.setCreateTime(diaryBean.getCreateTime());
                                        startRecordDetailActivity(recordBean);
                                    }
                                });

                            }else{
                                Toast.makeText(MyCollectionActivity.this, "您还没有收藏过日记哦", Toast.LENGTH_SHORT).show();
                            }


                        }else {
                            Toast.makeText(MyCollectionActivity.this, "服务器错误", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

    }
    private void startRecordDetailActivity(RecordBean recordBean) {
        Intent intent = new Intent(MyCollectionActivity.this, RecordDetailActivity.class);
        intent.putExtra("recordBean",recordBean);
        startActivity(intent);
    }

    /**
     * 使用：android-layout-finder 在线生成findViewById
     * Find the Views in the layout<br />
     * <br />
     * Auto-created on 2021-11-30 22:48:08 by Android Layout Finder
     * (http://www.buzzingandroid.com/tools/android-layout-finder)
     */
    private void findViews() {
        myCollectionTitle = (LinearLayout)findViewById( R.id.my_collection_title );
        ibMyCollectionBack = (ImageButton)findViewById( R.id.ib_my_collection_back );
        SplitLine = (View)findViewById( R.id.Split_line );
        gvMyCollection = (GridView)findViewById( R.id.gv_my_collection );

        ibMyCollectionBack.setOnClickListener( this );
    }

    /**
     * Handle button click events<br />
     * <br />
     * Auto-created on 2021-11-30 22:48:08 by Android Layout Finder
     * (http://www.buzzingandroid.com/tools/android-layout-finder)
     */
    @Override
    public void onClick(View v) {
        if ( v == ibMyCollectionBack ) {
            // Handle clicks for ibMyCollectionBack
            finish();
        }
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }
}